<template>
  <el-form ref="form" label-width="100px" :inline="false">
    <el-form-item label="SPU名称">
      <el-input
        v-model="SpuParams.spuName"
        placeholder="请你输入名称"
        clearable
        @change=""
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select
        v-model="SpuParams.tmId"
        value-key=""
        placeholder=""
        style="width: 200px"
      >
        <el-option
          :value="item.id"
          v-for="item in AllTradeMark"
          :key="item.id"
          :label="item.tmName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        v-model="SpuParams.description"
        type="textarea"
        placeholder="请你输入描述"
        clearable
        @change=""
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU照片">
      <!-- v-model:file-list 默认展示图片的列表
            action:上传图片的接口地址
            list-type:文件列表的类型
        -->
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handleUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img w-full alt="Preview Image" :src="dialogImageUrl" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <!-- 添加销售属性的下拉菜单 -->
      <el-select
        v-model="saleAttrIdAndValueName"
        :placeholder="
          unSelectSaleAttr.length
            ? `还未选择${unSelectSaleAttr.length}个`
            : '无'
        "
        style="width: 200px"
      >
        <el-option
          v-for="item in unSelectSaleAttr"
          :value="`${item.id}:${item.name}`"
          :key="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-button
        :disabled="saleAttrIdAndValueName ? false : true"
        type="primary"
        size="default"
        @click="addSaleAttr"
        icon="Plus"
        style="margin-left: 10px"
      >
        添加属性值
      </el-button>
      <!-- table展示销售属性与属性值的地方 -->
      <el-table :data="saleAttr" border stripe style="margin: 10px 0">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="销售属性名"
          prop="saleAttrName"
          width="100px"
        ></el-table-column>
        <el-table-column label="销售属性值">
          <!-- row为当前SPU已有的销售属性对象 -->
          <template #="{ row }">
            <el-tag
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              type="danger"
              effect="dark"
              closable
              style="margin: 0 5px"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.flag"
              v-model="row.saleAttrValue"
              placeholder="占位"
              size="small"
              clearable
              @change=""
              @blur="toLook(row)"
              style="width: 100px"
            ></el-input>

            <el-button
              v-else
              type="primary"
              size="small"
              icon="Plus"
              @click="toEdit(row)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100px">
          <template v-slot="{ $index }">
            <el-button
              type="primary"
              size="small"
              @click="saleAttr.splice($index, 1)"
              icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="">
      <el-button
        :disabled="saleAttr.length > 0 ? false : true"
        type="primary"
        size="default"
        @click="save"
      >
        保存
      </el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import type {
  SaleAttrValue,
  AllTradeMark,
  HasSaleAttr,
  HasSaleAttrResponseData,
  SaleAttr,
  SaleAttrResponseData,
  SpuData,
  SpuHasImg,
  SpuImg,
} from '@/apis/product/spu/type'
import { computed, ref } from 'vue'
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqAllSaleAttr,
  reqSpuHasSaleAttr,
  reqAddOrupdateSpu,
} from '@/apis/product/spu/index.ts'
import { TradeMark } from '@/apis/product/trademark/type'
import { ElMessage } from 'element-plus'

//自定义事件发射
let $emit = defineEmits(['changeScene'])

//存储已有的SPU数据
let AllTradeMark = ref<TradeMark[]>([])
//商品图片
let imgList = ref<SpuImg[]>([])
//已有的SPU销售属性
let saleAttr = ref<SaleAttr[]>([])
//全部销售属性
let allSaleAttr = ref<HasSaleAttr[]>([])

//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)

//存储预览图片的地址
let dialogImageUrl = ref<string>('')

//将来手机还未选择的销售属性的ID与属性值的名字
let saleAttrIdAndValueName = ref<string>('')

//存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: '', //三级分类ID
  spuName: '', //SPU名字
  description: '', //SPU的描述
  tmId: '', //品牌ID
  spuImageList: [],
  spuSaleAttrList: [],
})

//点击取消按钮，通知父组件切换场景值
const cancel = () => {
  $emit('changeScene', {
    flag: 0,
    params: SpuParams.value.id ? 'update' : 'add',
  })
}

//子组件定义获取数据的方法
const initHasSpuData = async (spu: SpuData) => {
  //spu即为父组件传递进来的数据
  //存储已有的SPU对象，将来在模板中展示
  SpuParams.value = spu
  //获取全部品牌的数据
  let result: AllTradeMark = await reqAllTradeMark()
  //获取品牌下全部售卖商品图片
  let result1: SpuHasImg = await reqSpuImageList(spu.id as number)
  //获取已有SPU销售属性的数据
  let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  //获取整个项目全部的销售属性
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  //存储全部品牌的数据
  AllTradeMark.value = result.data
  //SPU对应商品图片
  imgList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  //存储已有的SPU的销售属性
  saleAttr.value = result2.data
  //存储全部销售属性
  allSaleAttr.value = result3.data
}

//照片墙点击预览按钮时触发的钩子
const handlePictureCardPreview = (file: any) => {
  console.log(file)
  dialogImageUrl.value = file.url
  //点击弹出对话框
  dialogVisible.value = true
}

//上传成功之前的钩子，约束文件的大小与类型
const handleUpload = (file: any) => {
  if (file.type === 'image/png' || 'image/jpg' || 'image/jpeg') {
    return true
  } else {
    ElMessage({
      type: 'error',
      message: '文件类型错误',
    })
    return false
  }
}

//照片墙删除文件钩子
const handleRemove = () => {
  console.log(123)
}

//计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  //全部销售属性：颜色、版本、尺码
  //已有的销售属性：颜色、版本
  let unSelectAttr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item.name !== item1.saleAttrName
    })
  })
  return unSelectAttr
})

//添加销售属性的方法
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  //准备一个新的销售属性对象，将来带给服务器即可
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  //追加到数组当中
  saleAttr.value.push(newSaleAttr)
  //清空收集的数据
  saleAttrIdAndValueName.value = ''
}

//属性值按钮的点击事件
const toEdit = (row: SaleAttr) => {
  //点击按钮的时候，input组件显示
  row.flag = true
  //收集属性值
  row.saleAttrValue = ''
}
//表单元素失去焦点的回调
const toLook = (row: SaleAttr) => {
  //整理手机的属性的id与属性的名字
  const { baseSaleAttrId, saleAttrValue } = row
  //整理成服务器需要的属性值形式
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }
  //非法情况判断
  //判断为空
  if ((saleAttrValue as string).trim() === '') {
    ElMessage({
      type: 'error',
      message: '不能为空',
    })
    return
  }
  //判断是否重复
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === saleAttrValue
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值重复',
    })
    return
  }

  //追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  //切换为查看模式
  row.flag = false
}
//保存按钮的回调
const save = async () => {
  //整理参数
  //1.照片墙的数据
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  //2.整理销售属性的数据
  SpuParams.value.spuSaleAttrList = saleAttr.value
  //发请求
  let result = await reqAddOrupdateSpu(SpuParams.value)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '更新成功' : '添加成功',
    })
    //通知父组件切换场景
    $emit('changeScene', {
      flag: 0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '更新失败' : '添加失败',
    })
  }
}

const clearData = () => {
  //清空SpuParams数据
  Object.assign(SpuParams.value, {
    category3Id: '', //三级分类ID
    spuName: '', //SPU名字
    description: '', //SPU的描述
    tmId: '', //品牌ID
    spuImageList: [],
    spuSaleAttrList: [],
  })
  //清空照片墙
  imgList.value = []
  //清空销售属性
  saleAttr.value = []
  //清空商品id和属性值的数据
  saleAttrIdAndValueName.value = ''
  //清空id
  SpuParams.value.category3Id = ''
}

//添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  clearData()
  //存储三级分类ID
  SpuParams.value.category3Id = c3Id
  //获取全部品牌的数据
  let result: AllTradeMark = await reqAllTradeMark()
  //获取整个项目全部的销售属性
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()

  //存储数据
  AllTradeMark.value = result.data
  allSaleAttr.value = result3.data
}

//对外暴露方法
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style lang="scss" scoped></style>
